/**
 * Copyright 2018
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.dream.inspect.modules.sys.service.impl;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.dream.inspect.common.utils.StringUtil;
import com.dream.inspect.modules.dream.dao.SysUserMapper;
import com.dream.inspect.modules.dream.pojo.SysUserFormMap;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.dream.inspect.common.annotation.DataFilter;
import com.dream.inspect.common.utils.Constant;
import com.dream.inspect.common.utils.PageUtils;
import com.dream.inspect.common.utils.Query;
import com.dream.inspect.modules.sys.dao.SysUserDao;
import com.dream.inspect.modules.sys.entity.SysDeptEntity;
import com.dream.inspect.modules.sys.entity.SysUserEntity;
import com.dream.inspect.modules.sys.service.SysDeptService;
import com.dream.inspect.modules.sys.service.SysUserRoleService;
import com.dream.inspect.modules.sys.service.SysUserService;
import com.dream.inspect.modules.sys.shiro.ShiroUtils;


/**
 * 系统用户
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年9月18日 上午9:46:09
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysUserMapper sysUserDao;

    @Override
    public List<Long> queryAllMenuId(Long userId) {
        return baseMapper.queryAllMenuId(userId);
    }

    @Override
    @DataFilter(subDept = true, user = false)
    public PageUtils queryPage(Map<String, Object> params) {
        String username = (String) params.get("username");
        if (StringUtil.isNotEmpty(username)) {
            username=username.trim();
        }
        Page<SysUserEntity> page = this.selectPage(
                new Query<SysUserEntity>(params).getPage(),
                new EntityWrapper<SysUserEntity>()
                        .like(StringUtils.isNotBlank(username), "username", username)
                        .like("user_flag", "1")
                        .addFilterIfNeed(params.get(Constant.SQL_FILTER) != null, (String) params.get(Constant.SQL_FILTER))
        );

        for (SysUserEntity sysUserEntity : page.getRecords()) {

            SysDeptEntity sysDeptEntity = sysDeptService.selectById(sysUserEntity.getDeptId());
            if (sysDeptEntity != null) {
                sysUserEntity.setDeptName(sysDeptEntity.getName());
            }
        }

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysUserEntity user) {
        user.setCreateTime(new Date());
        //sha256加密
        String salt = RandomStringUtils.randomAlphanumeric(20);
        user.setSalt(salt);
        user.setUserFlag("1");
        user.setPassword(ShiroUtils.sha256(user.getPassword(), user.getSalt()));
        this.insert(user);

        //保存用户与角色关系
        sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysUserEntity user) {
        if (StringUtils.isBlank(user.getPassword())) {
            user.setPassword(null);
        } else {
            user.setPassword(ShiroUtils.sha256(user.getPassword(), user.getSalt()));
        }
        List<Long> roleIdList = user.getRoleIdList();

        this.updateById(user);
        if (roleIdList != null && roleIdList.size() > 0) {
            //保存用户与角色关系
            sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
        }
    }


    @Override
    public boolean updatePassword(Long userId, String password, String newPassword) {
        SysUserEntity userEntity = new SysUserEntity();
        userEntity.setPassword(newPassword);
        return this.update(userEntity,
                new EntityWrapper<SysUserEntity>().eq("user_id", userId).eq("password", password));
    }

    @Override
    public List<SysUserFormMap> getUserLise(String deptId, String name, int currPage, int pageSize, String flag) {
        List<SysUserFormMap> userList = new ArrayList<SysUserFormMap>();
        if ("".equals(currPage + "") || "".equals(pageSize + "")) {
            userList = sysUserDao.queryUserListByPage(deptId, name, 0, 0, flag);
        } else {
            userList = sysUserDao.queryUserListByPage(deptId, name, (currPage - 1) * pageSize, pageSize, flag);
        }
        return userList;
    }

    @Override
    public SysUserEntity selectSysUserById(SysUserEntity sysUserEntity) {

        SysUserEntity suEntity = this.baseMapper.selectSysUserById(sysUserEntity);

        return suEntity;
    }

}
